import { useEffect, useState } from "react";
import Taro from "@tarojs/taro";
import { Text, View, Image } from "@tarojs/components";
import { Button, DatePicker, Picker, Tag } from "@nutui/nutui-react-taro";
import InfiniteLoading from "../../components/InfiniteLoading";
import InfiniteLoadingFoot from "../../components/InfiniteLoadingFoot";
import usePage from "../../hooks/usePage";
import { iconClear, iconClockBlack, iconDownGray } from "../../assets/files";
import dayjs from "dayjs";


import { pageTrainingInfo } from "../../api/apply";
import { navigateTo } from "../../common/_";
import { getSystemDictValue } from "../../utils/globalData";
// import NavTab from "../../components/navTab";
import useNavInfo from "../../hooks/useNavInfo";
import "./index.scss";

definePageConfig({
  navigationBarTitleText: "测试记录",
  disableScroll: true,
});

export default function DangerList(props) {
  const [timeStartVisible, setTimeStartVisible] = useState(false);
  const [timeEndVisible, setTimeEndVisible] = useState(false);
  const [timeType, setTimeType] = useState();
  const [params, setParams] = useState({
    startDate: dayjs().subtract(151, 'day').format('YYYY-MM-DD'),
    endDate: dayjs().add(31, 'day').startOf('day').format('YYYY-MM-DD'),
    auditState: "",
    pageSize: 10,
    date: ""
  });
  const { listData, refreshing, empty, loadMore, onPull, onLoad } = usePage({
    request: pageTrainingInfo,
    params,
  });

  const [shenqStatus, setShenqStatus] = useState([
    {
      id: "",
      name: "全部",
      color: '#FF8916',
      bgColor: 'rgba(255, 212, 148, 0.3)'
    },
    {
      id: 1,
      name: "审核中",
      color: '#FF8916',
      bgColor: 'rgba(255, 212, 148, 0.3)'
    },
    {
      id: 2,
      name: "待培训",
      color: '#6486FF',
      bgColor: 'rgba(148, 197, 255, 0.5)'
    },
    {
      id: 3,
      name: "已拒绝",
      color: '#FF1616',
      bgColor: 'rgba(255, 148, 148, 0.5)'
    },
    {
      id: 4,
      name: "已培训",
      color: 'rgba(7, 193, 96, 1)',
      bgColor: 'rgba(176, 255, 214, 0.35)'
    },
  ]);

  useEffect(() => {
    Taro.eventCenter.on('reList', handleUpdate);

    return () => {
      Taro.eventCenter.off('reList', handleUpdate);
    }
  }, [])

  const handleUpdate = () => {
    setParams({
      ...params,
      date: new Date()
    })
  }

  const navigateToDetails = (item) => {
    navigateTo('/pages/apply-detail/index', item)
  };

  function selectTime(type) {
    setTimeType(type);
    if (type === "start") {
      setTimeStartVisible(true);
    } else {
      setTimeEndVisible(true);
    }
  }

  function confirmTime(values, options) {
    console.log(values, options);
    let data = ""
    if (values.join("-").includes("02-31") || values.join("-").includes("02-30")) {
      data = dayjs().year() + '-02-01'
    } else {
      data = values.join("-")
    }
    if (timeType === "start") {
      setParams({
        ...params,
        startDate: data
      })
    } else {
      setParams({
        ...params,
        endDate: data
      })
    }
  }

  const [visible, setVisible] = useState(false)
  const [baseDesc, setBaseDesc] = useState('')
  const listData1 = [
    [
      { value: "", text: '全部' },
      { value: 1, text: '审核中' },
      { value: 2, text: '待培训' },
      { value: 3, text: '已拒绝' },
      { value: 4, text: '已培训' },
    ],
  ]

  const changePicker = (list, option, columnIndex) => {
    console.log(columnIndex, option)
  }
  const confirmPicker = (
    options,
    values
  ) => {
    setParams({
      ...params,
      auditState: values[0] ? parseInt(values[0]) : ""
    })
  }

  function matchType(type) {
    for (let index = 0; index < shenqStatus.length; index++) {
      const element = shenqStatus[index];
      if (element.id == type) {
        return element
      }

    }
  }

  const toApply = (e, item) => {
    e.stopPropagation()
    const { changeCur } = props
    // changeCur(1, item)
    navigateTo('/pages/apply/index', item)
    // Taro.reLaunch({
    //   url:'/pages/apply/index'
    // })
  }

  const [cur, setCur] = useState("")
  const { statusBarHeight } = useNavInfo();

  const clearTimeout = () => {
    setParams({
      ...params,
      startDate: "",
      endDate: "",
    })
  }

  return (
    <View className={"reservation-record-page"}>
      {/* <NavTab
        defaultValue={2}
        tabList={[{ name: '培训申请', id: 1 }, { name: '培训记录', id: 2 }]}
        onChangeCallback={(cur)=>{
        }}
      /> */}
      <View className="topSelectWrap">
        <View className="timeWrap">
          <Image src={iconClockBlack} className="clockSty" />
          <Text className="timeText" onClick={() => selectTime("start")}>
            {params.startDate || '请选择'}
          </Text>
          <Text className="zhi">至</Text>
          <Text className="timeText" onClick={() => selectTime('end')}>{params.endDate || '请选择'}</Text>
          <Image onClick={() => clearTimeout()} src={iconClear} className="iconClose" />
        </View>
        <View className="shai" onClick={() => {
          setVisible(true)
        }}>
          <Text>{matchType(params.auditState).name}</Text>
          <Image src={iconDownGray} className="downSty" />
        </View>
      </View>

      <View className={"list-wrapper"}>
        <InfiniteLoading
          empty={empty}
          onLoad={onLoad}
          onRefresh={onPull}
          refreshing={refreshing}
        >
          {listData?.map((item) => (
            <View
              className={"list-item"}
              onClick={() => navigateToDetails(item)}
            >
              <View className="tie">
                <View className="iteWrap" style={{ flex: 1 }}>
                  <Text className="tit"> 培训时间：</Text>
                  <Text className="ites">
                    {item.trainingTime?.substr(0, 16)}
                  </Text>
                  <Text className="reTypeText" style={{ color: matchType(item.auditState).color, backgroundColor: matchType(item.auditState).bgColor }}>
                    {matchType(item.auditState).name}
                  </Text>
                </View>
                {/* <Text className="rightDes">
                  {item.startTime}
                </Text> */}
                {/* <Image className="rightIcon" src={iconRightGray} /> */}
              </View>
              <View className="content">
                <View className="gonggsiWrap">
                  <Tag className="itemTag" background="#2A64F4" plain>{getSystemDictValue(77, item?.category)?.name}</Tag>
                  <Text className="companyName" style={{ marginLeft: '2px' }}>{item.enterpriseName}</Text>
                </View>
                <View>
                  <Text className="pNum">培训人数：{item.number}</Text>
                  <Text className="pNum" style={{ marginLeft: 12 }}>辖区：{getSystemDictValue(13, item?.jurisdiction)?.name}</Text>
                </View>
              </View>

              {
                item.auditState === 3 &&
                <View className="btnWrap">
                  <Text>拒绝原因：{item.auditReason}</Text>
                  <Button onClick={(e) => toApply(e, item)} type="info" style={{}}>重新申请</Button>
                </View>
              }

            </View>
          ))}
          {listData?.length > 0 && <InfiniteLoadingFoot state={loadMore} />}
        </InfiniteLoading>
      </View>

      {/* <Button className="AddBtn" block size="large" type="info" style={{}} onClick={() => {
        navigateTo("/pages/apply/index")
      }}>新增培训申请</Button> */}


      <DatePicker
        title="选择日期"
        visible={timeStartVisible}
        defaultValue={new Date(params.startDate)}
        showChinese
        onClose={() => {
          setTimeStartVisible(false);
        }}
        onConfirm={(options, values) => confirmTime(values, options)}
      />

      <DatePicker
        title="结束日期"
        visible={timeEndVisible}
        defaultValue={new Date(params.endDate)}
        showChinese
        onClose={() => { setTimeEndVisible(false) }}
        onConfirm={(options, values) => confirmTime(values, options)}
      />

      <Picker
        title="状态筛选"
        visible={visible}
        options={listData1}
        onConfirm={(list, values) => confirmPicker(list, values)}
        onClose={() => setVisible(false)}
        onChange={changePicker}
      />
    </View>
  );
}
